// 网络管理器
class NetworkManager {
    constructor(roomCode, isHost = false) {
        this.roomCode = roomCode;
        this.isHost = isHost;
        this.socket = null;
        this.playerId = null;
        this.connected = false;
        
        this.init();
    }

    init() {
        // 模拟Socket.IO连接
        this.simulateConnection();
        
        // 设置事件监听
        this.setupEventListeners();
    }

    simulateConnection() {
        // 模拟连接成功
        setTimeout(() => {
            this.connected = true;
            this.playerId = 'player_' + Math.random().toString(36).substr(2, 9);
            console.log('Connected to room:', this.roomCode);
            
            // 触发连接成功事件
            if (this.onConnect) {
                this.onConnect();
            }
        }, 1000);
    }

    setupEventListeners() {
        // 模拟接收其他玩家加入
        setTimeout(() => {
            if (this.onPlayerJoin) {
                this.onPlayerJoin({
                    id: 'other_player_1',
                    x: 200,
                    y: 150,
                    name: '其他玩家'
                });
            }
        }, 2000);

        // 模拟接收方块更新
        setInterval(() => {
            if (Math.random() < 0.1 && this.onBlockUpdate) {
                const x = Math.floor(Math.random() * 32);
                const y = Math.floor(Math.random() * 32);
                const type = Math.floor(Math.random() * 5) + 1;
                const action = Math.random() < 0.5 ? 'mine' : 'place';
                
                this.onBlockUpdate(x, y, type, action);
            }
        }, 3000);
    }

    // 发送方块挖掘
    mineBlock(x, y) {
        if (!this.connected) return;
        
        console.log('Mining block at:', x, y);
        
        // 模拟发送到服务器
        setTimeout(() => {
            // 广播给其他玩家
            this.broadcastBlockUpdate(x, y, null, 'mine');
        }, 100);
    }

    // 发送方块放置
    placeBlock(x, y, type) {
        if (!this.connected) return;
        
        console.log('Placing block at:', x, y, 'type:', type);
        
        // 模拟发送到服务器
        setTimeout(() => {
            // 广播给其他玩家
            this.broadcastBlockUpdate(x, y, type, 'place');
        }, 100);
    }

    // 发送位置更新
    updatePosition(x, y) {
        if (!this.connected) return;
        
        // 模拟发送到服务器
        setTimeout(() => {
            this.broadcastPlayerMove(x, y);
        }, 50);
    }

    // 广播方块更新
    broadcastBlockUpdate(x, y, type, action) {
        // 模拟广播给其他玩家
        if (this.onBlockUpdate) {
            this.onBlockUpdate(x, y, type, action);
        }
    }

    // 广播玩家移动
    broadcastPlayerMove(x, y) {
        // 模拟广播给其他玩家
        if (this.onPlayerMove) {
            this.onPlayerMove(this.playerId, x, y);
        }
    }

    // 保存游戏状态
    saveGame() {
        if (!window.game || !window.game.scene.scenes[0]) return;
        
        const gameScene = window.game.scene.scenes[0];
        const saveData = {
            inventory: gameScene.inventory,
            playerPosition: {
                x: gameScene.player.x,
                y: gameScene.player.y
            },
            timestamp: Date.now()
        };
        
        // 保存到本地存储
        localStorage.setItem('pixel_game_save', JSON.stringify(saveData));
        
        // 模拟保存到云端
        this.saveToCloud(saveData);
    }

    // 加载游戏状态
    loadGame() {
        const saveData = localStorage.getItem('pixel_game_save');
        if (saveData) {
            const data = JSON.parse(saveData);
            return data;
        }
        
        // 尝试从云端加载
        return this.loadFromCloud();
    }

    // 模拟云端保存
    saveToCloud(data) {
        console.log('Saving to cloud:', data);
        
        // 模拟API调用
        setTimeout(() => {
            console.log('Game saved to cloud successfully');
        }, 500);
    }

    // 模拟云端加载
    loadFromCloud() {
        console.log('Loading from cloud...');
        
        // 模拟API调用
        return new Promise((resolve) => {
            setTimeout(() => {
                const cloudData = {
                    inventory: { wood: 10, stone: 5, coal: 3 },
                    playerPosition: { x: 256, y: 200 }
                };
                resolve(cloudData);
            }, 500);
        });
    }

    // 断开连接
    disconnect() {
        this.connected = false;
        console.log('Disconnected from room:', this.roomCode);
        
        if (this.onDisconnect) {
            this.onDisconnect();
        }
    }
}

// 事件回调
NetworkManager.prototype.onConnect = null;
NetworkManager.prototype.onDisconnect = null;
NetworkManager.prototype.onPlayerJoin = null;
NetworkManager.prototype.onPlayerLeave = null;
NetworkManager.prototype.onPlayerMove = null;
NetworkManager.prototype.onBlockUpdate = null;

// 自动保存
setInterval(() => {
    if (window.network && window.network.connected) {
        window.network.saveGame();
    }
}, 30000); // 每30秒自动保存一次

// 页面卸载时保存
window.addEventListener('beforeunload', () => {
    if (window.network) {
        window.network.saveGame();
        window.network.disconnect();
    }
});